package com.lzj.server.utils;


import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisQueueUtils {
    private final RedissonClient redissonClient;

    RedisQueueUtils(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    // 普通队列（FIFO）
    public <T> void addToQueue(String queueName, T data) {
        RQueue<T> queue = redissonClient.getQueue(queueName);
        queue.add(data);
    }

    public <T> T pollFromQueue(String queueName) {
        RQueue<T> queue = redissonClient.getQueue(queueName);
        return queue.poll();
    }

    // 延迟队列（延迟到期自动加入目标队列）
    public <T> void addToDelayedQueue(String delayQueueName, String targetQueueName, T data, long delay, TimeUnit unit) {
        RBlockingQueue<T> targetQueue = redissonClient.getBlockingQueue(targetQueueName);
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(targetQueue);
        delayedQueue.offer(data, delay, unit);
    }

    // 处理延迟队列：消费者阻塞等待
    public <T> T takeFromBlockingQueue(String targetQueueName) throws InterruptedException {
        RBlockingQueue<T> queue = redissonClient.getBlockingQueue(targetQueueName);
        return queue.take(); // 阻塞直到有数据
    }
}